<template>
  <div class="exam-review">
    <div class="container">
      <ExamNavBar :examId="examId" :semesterId="semesterId" :showNav="false" />

      <div class="content-layout">
        <!-- 左侧部分：学生信息 + 筛选器 + 题号导航 -->
        <div class="left-panel">
          <div class="student-info">
            <img :src="studentInfo.avatar" alt="学生头像" class="avatar">
            <div>
              <p>姓名：<strong>{{ studentInfo.name }}</strong></p>
              <p>学号：<strong>{{ studentInfo.number }}</strong></p>
              <p>分班：<strong>{{ studentInfo.class }}</strong></p>
            </div>
            <span :class="markStatus === 1 ? 'reviewed' : 'unreviewed-tag'">
              {{ markStatus === 1 ? '已评阅' : '未评阅' }}
            </span>
          </div>

          <!-- 筛选器 -->
          <div class="filter-options">
            <h4>答题卡</h4>
            <div style="margin:15px 20px">
                <label class="switch">
                <input type="checkbox" v-model="showWrongOnly">
                <span class="slider round"></span>
                </label>
                <span>仅显示错题</span>
            </div>
            <div style="margin:15px 20px">
                <label class="switch">
                <input type="checkbox" v-model="showSubjectiveOnly">
                <span class="slider round"></span>
                </label>
                <span>仅显示主观题</span>
            </div>
                  <!-- 提示用户颜色的含义 -->
            <div class="color-legend">
                <div class="legend-item">
                <span class="color-box correct"></span>
                <span>正确题目</span>
                </div>
                <div class="legend-item">
                <span class="color-box wrong"></span>
                <span>错误题目</span>
                </div>
                <div class="legend-item">
                <span class="color-box subjective"></span>
                <span>主观题</span>
                </div>
            </div>
          </div>
          <!-- 题号导航 -->
          <div class="question-navigation">
            <h4>题号导航</h4>
            <div class="question-numbers">
              <span v-for="(question, index) in questions" :key="index"
                    @click="scrollToQuestion(index)"
                    :class="{
                        'wrong-question': question.studentScore < question.score && question.type !== 'qna',
                        'correct-question': question.studentScore === question.score && question.type !== 'qna',
                        'subjective-question': question.type === 'qna'
                    }"
                    class="question-number">
                {{ index + 1 }}
              </span>
            </div>
          </div>
        </div>

        <!-- 右侧部分：分数条 + 题目详细作答 -->
        <div class="right-panel">
          <!-- 分数条 -->
          <div class="score-bar">
            <table>
              <thead>
                <tr>
                  <th>题号</th> 
                  <th v-for="(question, index) in questions" :key="'header' + index">{{ index + 1 }}</th>
                  <th>总分</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <th>应得分</th>
                  <td v-for="(question, index) in questions" :key="'score' + index">{{ question.score }}</td>
                  <td class="total-score">{{ totalExpectedScore }}</td>
                </tr>
                <tr>
                  <th>实得分</th>
                  <td v-for="(question, index) in questions" :key="'studentScore' + index">{{ question.studentScore }}</td>
                  <td class="total-score">{{ totalStudentScore }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 题目展示 -->
          <div class="questions">
            <div v-if="!hasSubmission" class="empty-tips">
              <img src="@/assets/picture/notips.png" class="no-data-img" />
              <p style="text-align:center;color:gray;margin-top:10px;">尚未提交试卷</p>
            </div>
            <template v-else>
              <div v-for="(question, index) in filteredQuestions" :key="index" class="question" :id="'question-' + index">
                <div class="box-flex">
                  <h4>{{ index + 1 }}. {{ question.title }}（{{ question.score }}分）</h4>
                  <span class="score-box">
                    <input type="number"
                          v-model.number="question.studentScore"
                          :max="question.score"
                          min="0"
                          class="score-input"/> /
                    {{ question.score }} 分
                  </span>
                </div>

                <!-- 选择题 -->
                <ul v-if="question.options">
                  <li v-for="option in question.options" :key="option.key"
                      :class="{
                        'correct-answer': option.isCorrect,
                        'student-wrong': option.selected && !option.isCorrect,
                        'student-correct': option.selected && option.isCorrect
                      }">
                    <input type="radio" :checked="option.selected" disabled>
                    {{ option.text }}
                  </li>
                </ul>

                <!-- 简答题 -->
                <div v-if="question.type === 'qna'" class="subjective-answer">
                  <div class="student-answer">
                    <h5>学生作答：</h5>
                    <div v-html="question.studentAnswer"></div>
                  </div>
                  <div class="reference-answer">
                    <h5>参考答案：</h5>
                    <div v-html="question.correctAnswer"></div>
                  </div>
                </div>
              </div>
              <div style="text-align:right; margin:20px 0">
                <button @click="cancelEdit" class="cancel-button">取消</button>
                <button class="submit-button" @click="submitScores">提交</button>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router'; 
import { ElMessage } from "element-plus";
import ExamNavBar from '@/components/ExamNavBar.vue';
import { fetchAnswerReviewDetail,submitExamScores  } from '@/services/api';

export default {
  components: { ExamNavBar },
  setup() {
    const route = useRoute();
    const router  = useRouter();
    const examId = route.params.examId;
    const semesterId = route.params.semesterId;
    const studentInfo = ref({});
    const questions = ref([]);
    const showWrongOnly = ref(false);
    const showSubjectiveOnly = ref(false);
    const stuExamId = ref(route.query.stu_exam_id ?? null);
    const markStatus = ref(Number(route.query.mark_status ?? 0)); 

    // 去除HTML标签的函数
    const removeHtmlTags = (text) => {
      return text.replace(/<\/?[^>]+(>|$)/g, ""); // 正则去除所有HTML标签
    };
    const hasSubmission = computed(() => questions.value.length > 0);
    const fetchData = async () => {
      if (!stuExamId.value) return;
      try {
        const response = await fetchAnswerReviewDetail({
          sem_id: route.params.semesterId,
          stu_exam_id: route.query.stu_exam_id,
          paper_id: route.query.paper_id
        });

        if (response.data.status === 1) {
          const data = response.data.data;
          studentInfo.value = {
            name: data.student.username,
            number: data.student.stu_number,
            class: data.student.division_name,
            avatar: data.student.img_url,
          };

          questions.value = data.qsList.flatMap(qsGroup => qsGroup.items.map(item => ({
            title: item.qs_title.replace(/<\/?p>/g, ''), // 去除多余的<p>标签
            stu_qs_id: item.stu_qs_id, 
            score: item.q_score || 0,
            type: item.qs_type,
            options: item.options?.map(opt => ({
              key: opt.option_id,
              text: opt.option_content,
              selected: opt.stu_choosed,
              isCorrect: opt.is_right
            })) || [],
            studentAnswer: item.stu_ans,
            correctAnswer: item.qna_ans,
            studentScore: item.stu_score || 0
          })));
        }
      } catch (err) {
        console.error("网络请求异常:", err.message);
      }
    };

    onMounted(fetchData);

    const filteredQuestions = computed(() => {
      return questions.value.filter(q => {
        if (showWrongOnly.value && q.studentScore === q.score) return false; // 只显示错题
        if (showSubjectiveOnly.value && q.type !== 'qna') return false; // 只显示主观题
        return true;
      });
    });

    const totalExpectedScore = computed(() => {
      return questions.value.reduce((sum, q) => sum + (q.score || 0), 0);
    });

    const totalStudentScore = computed(() => {
      return questions.value.reduce((sum, q) => sum + (q.studentScore || 0), 0);
    });

    const scrollToQuestion = (index) => {
      document.getElementById(`question-${index}`)?.scrollIntoView({ behavior: "smooth" });
    };
    const submitScores = async () => {
      try{
        const payload = {
          stu_exam_id : route.query.stu_exam_id,
          examStuQs   : questions.value.map(q => ({
            stu_qs_id : q.stu_qs_id,
            stu_score : q.studentScore ?? 0
          }))
        }
        const { data } = await submitExamScores(payload)
        if (data.status === 1){
          ElMessage.success('批阅成功！');
           markStatus.value = 1;
           setTimeout(() => router.back(), 600);
        }else{
          ElMessage.error(data.msg || '提交失败')
        }
      }catch(e){
        ElMessage.error('网络错误，请稍后再试')
        console.error(e)
      }
    };
    const cancelEdit = () => {
      router.back();
    };

    return { examId, markStatus,semesterId, studentInfo, questions, showWrongOnly, showSubjectiveOnly, cancelEdit,hasSubmission,
             filteredQuestions, scrollToQuestion, totalExpectedScore, totalStudentScore, removeHtmlTags, submitScores };
  }
};
</script>

<style scoped>
.unreviewed-tag {
  position: absolute;
  top: 50px;
  right: 0;
  background: #e0e0e0;
  color: #555;
  font-weight: bold;
  padding: 5px 15px;
  transform: rotate(45deg);
  transform-origin: top right;
  border-radius: 3px;
  font-size: 14px;
}
.left-panel  { width: 300px; /* …其余同学端 */ }
.right-panel { flex: 1 1 0; min-width: 0; }

.score-bar {
  overflow-x: auto;
  max-width : 100%;
}
.score-bar table {
  width: max-content;
  min-width: 100%;
}
.empty-tips {
  display:flex; flex-direction:column; align-items:center; justify-content:center; height:400px;
}
.no-data-img { width:200px; opacity:.4; }
.score-box{
  display:inline-flex;
  align-items:center;
  gap:4px;
}

/* 让输入框看起来仍是蓝底白字的小胶囊 */
.score-input{
  width: 55px;
  text-align:center;
  border: none;
  background: transparent;
  color:#fff;
  font-weight:bold;
  outline:none;
  font-size: 17px;
}
.exam-review {
  display: flex;
  justify-content: center;
  background: #E3F2FD;
  padding: 20px;
}

.container {
  width: 85vw;
  background: #ffffff;
  padding: 20px;
  border-radius: 8px;
}

.content-layout {
  display: flex;
  background: #f5f7fa;
}

/* 左侧面板 */
.left-panel {
  width: 25%;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
}

.student-info {
  display: flex;
  align-items: center;
  background: #ffffff;
  padding: 15px;
  border-radius: 8px;
  position: relative; /* 使得绝对定位的元素相对于该元素定位 */
}

.reviewed {
  position: absolute;
  top: 50px; /* 距离上边缘 */
  right: 0px; /* 距离右边缘 */
  background: #42A5F5; /* 绶带背景色 */
  color: #fff; /* 白色字体 */
  font-weight: bold;
  padding: 5px 15px;
  transform: rotate(45deg); /* 使标签倾斜 */
  transform-origin: top right; /* 设置旋转中心点为右上角 */
  border-radius: 3px;
  font-size: 14px; /* 调整字体大小 */
}

.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 15px;
}



/* 筛选器 */
.filter-options {
  margin: 20px 0;
  padding: 10px;
  background: #ffffff;
  border-radius: 8px;
}

.filter-options label {
  margin-right: 10px;
  cursor: pointer;
}

.switch {
  position: relative;
  display: inline-block;
  width: 34px;
  height: 20px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: 0.4s;
  border-radius: 50px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 12px;
  width: 12px;
  border-radius: 50%;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: 0.4s;
}

input:checked + .slider {
  background-color: #42A5F5;
}

input:checked + .slider:before {
  transform: translateX(14px);
}

/* 提示色球 */
.color-legend {
  display: flex;
  justify-content: space-around;
  padding: 10px;
  background: #ffffff;
  border-radius: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
}

.color-box {
  width: 15px;
  height: 15px;
  border-radius: 50%;
  margin-right: 10px;
}

.correct {
  background-color: #66BB6A; /* 绿色 */
}

.wrong {
  background-color: #EF5350; /* 红色 */
}

.subjective {
  background-color: #42A5F5; /* 蓝色 */
}

/* 题号导航 */
.question-navigation {
  background: #ffffff;
  padding: 15px;
  border-radius: 8px;
}

.question-numbers {
  margin: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  min-height: 100px; /* 题号导航最小高度 */
}

.question-number {
  width: 35px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-weight: bold;
  border-radius: 50%;
  cursor: pointer;
  transition: background 0.3s;
}

.wrong-question {
  background: #EF5350;
}

.wrong-question:hover {
  background: #D32F2F;
}

/* 正确题 - 绿色 */
.correct-question {
  background: #66BB6A;
}

.correct-question:hover {
  background: #388E3C;
}

/* 简答题 - 蓝色 */
.subjective-question {
  background: #42A5F5;
}

.subjective-question:hover {
  background: #1976D2;
}



/* 右侧面板 */
.right-panel {
  flex-grow: 1;
  margin-right: 15px;
}

.score-bar {
  background: #ffffff;
  padding: 15px;
  border-radius: 8px;
  margin-top: 15px;
  margin-bottom: 20px;
  overflow-x: auto;
}

.score-bar table {
  width: 100%;
  border-collapse: collapse;
  text-align: center;
}

.score-bar th, .score-bar td {
  padding: 10px;
  border: 1px solid #ddd;
}

/* 表头样式 */
.score-bar thead {
  background: #42A5F5;
  color: white;
  font-weight: bold;
}

/* 让左侧列固定 */
.score-bar tbody th {
  background: #f5f7fa;
  font-weight: bold;
}



.questions {
  background: #ffffff;
  padding: 15px;
  border-radius: 8px;
}

/* 题目样式 */
.question {
  padding: 15px;
  border-bottom: 1px solid #ddd;
}

.question:last-child {
  border-bottom: none;
}

.score-box {
  display: inline-block;
  background: #42A5F5;
  color: #ffffff;
  padding: 5px 10px;
  border-radius: 5px;
  font-weight: bold;
  margin-top: 10px;
}

/* 选择题选项 */
ul {
  list-style: none;
  padding: 0;
}

li {
  padding: 8px;
  border-radius: 5px;
  margin: 5px 0;
  cursor: pointer;
}

.correct-answer {
  background: #84ff891f;
  color: #000000;
  border: solid 1px #00800040;
}

.student-wrong {
  background: #ff7e7e21;
  color: black;
  border: solid 1px #ff000029;
}

.student-correct {
  background: #85c6fa1a;
  color: black;
  border: solid 1px #257bb645;
}

/* 主观题样式 */
.subjective-answer {
  display: flex;
  gap: 15px;
  margin-top: 10px;
}

.student-answer, .reference-answer {
  width: 50%;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
}

.box-flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.cancel-button,
.submit-button {
  width: 100px;
  padding: 10px 15px;
  font-size: 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
.submit-button {
  background-color: #42A5F5;
  color: #fff;
  }
.cancel-button{
  margin-right: 25px;
  background-color: rgb(206, 206, 206);
  color:black

}
.cancel-button:hover{
  background-color: gray;
}
.submit-button:hover {
  background-color: #1e3661;
}
</style>
